<template>
  <view class="normal-login-container">
    <!-- LOGO + 标题 -->
    <view class="logo-content align-center justify-center flex">
      <image
        style="width: 100rpx;height: 100rpx;"
        :src="globalConfig.appInfo.logo"
        mode="widthFix"
      />
      <text class="title">员工入职注册</text>
    </view>

    <!-- 表单区域 -->
    <view class="login-form-content">
      <!-- 角色选择 -->
      <view class="input-item flex align-center">
        <view class="iconfont icon-role icon"></view>
        <view class="input">
          <picker
            mode="selector"
            :range="roles"
            range-key="roleName"
            :value="selectedRoleIndex"
            @change="onRoleChange"
          >
            <view class="picker-text">
              {{ selectedRoleIndex !== null
                   ? roles[selectedRoleIndex].roleName
                   : '请选择角色' }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 部门选择 -->
      <view class="input-item flex align-center">
        <view class="iconfont icon-dept icon"></view>
        <view class="input">
          <picker
            mode="selector"
            :range="deptList"
            range-key="deptName"
            :value="selectedDeptIndex"
            @change="onDeptChange"
          >
            <view class="picker-text">
              {{ selectedDeptIndex !== null && deptList.length > 0
                   ? deptList[selectedDeptIndex].deptName
                   : '请选择部门' }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 账号 -->
      <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input
          v-model="registerForm.username"
          class="input"
          type="text"
          placeholder="请输入艺名"
          maxlength="30"
        />
      </view>

      <!-- 业务员专属：工号和等级 -->
      <view v-if="registerForm.roleKey === 'yewuyuan'" class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input
          v-model="registerForm.employeeId"
          class="input"
          type="text"
          placeholder="请输入工号"
          maxlength="20"
        />
      </view>
      <view v-if="registerForm.roleKey === 'yewuyuan'" class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input
          v-model="registerForm.level"
          class="input"
          type="text"
          placeholder="请输入等级"
          maxlength="10"
        />
      </view>

      <!-- 密码 -->
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input
          v-model="registerForm.password"
          type="password"
          class="input"
          placeholder="请输入密码"
          maxlength="20"
        />
      </view>

      <!-- 重复密码 -->
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input
          v-model="registerForm.confirmPassword"
          type="password"
          class="input"
          placeholder="请输入重复密码"
          maxlength="20"
        />
      </view>

      <!-- 验证码 -->
      <view
        class="input-item flex align-center"
        style="width: 60%; margin: 0;"
        v-if="captchaEnabled"
      >
        <view class="iconfont icon-code icon"></view>
        <input
          v-model="registerForm.code"
          type="text"
          class="input"
          placeholder="请输入验证码"
          maxlength="4"
        />
        <view class="login-code">
          <image
            :src="codeUrl"
            @click="getCode"
            class="login-code-img"
          />
        </view>
      </view>

      <!-- 注册按钮 -->
      <view class="action-btn">
        <button
          @click="handleRegister"
          class="register-btn cu-btn block bg-blue lg round"
        >
          确定入职
        </button>
      </view>
    </view>

    <!-- 切换到登录 -->
    <view class="xieyi text-center">
      <text @click="handleUserLogin" class="text-blue">
        使用已有账号登录
      </text>
    </view>
  </view>
</template>

<script>
import { getCodeImg, register } from '@/api/login'
import { listDeptPublic } from '@/api/system/dept'

export default {
  data() {
    return {
      // 本地写死的角色列表
      roles: [
        { roleName: '业务员', roleKey: 'yewuyuan' },
         { roleName: 'DJ',  roleKey: 'dj' },
          { roleName: '服务员', roleKey: 'fuwuyuan' },
            { roleName: '吧员',  roleKey: 'bayuan' },
            { roleName: '发台员',  roleKey: 'fataiyuan' },
            { roleName: '发号员',   roleKey: 'fahaoyuan' },
            { roleName: '业务经理', roleKey: 'yewujinli' },
            { roleName: '考勤员',   roleKey: 'kaoqinyuan' },
        { roleName: '督察',   roleKey: 'duchayuan' },
        { roleName: '服务员',   roleKey: 'fuwuyuan' },
        { roleName: '管理层',   roleKey: 'guanliceng' },
        { roleName: '统计员',   roleKey: 'tongjiyuan' },
          
      ],
      selectedRoleIndex: null,
      
      // 部门相关
      deptList: [],
      selectedDeptIndex: null,

      codeUrl: '',
      captchaEnabled: true,
      globalConfig: getApp().globalData.config,
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        code: '',
        uuid: '',
        roleKey: '',  // 新增：角色编码
        ee: '',  // 新增：ee字段
        employeeId: '', // 新增：工号
        level: '', // 新增：等级
        deptId: '' // 新增：部门ID
      }
    }
  },
  created() {
    this.getCode()
    this.getDeptList()
  },
  methods: {
    // Picker 选中角色
    onRoleChange(e) {
      this.selectedRoleIndex = e.detail.value
      this.registerForm.roleKey = this.roles[this.selectedRoleIndex].roleKey
    },

    // Picker 选中部门
    onDeptChange(e) {
      this.selectedDeptIndex = e.detail.value
      this.registerForm.deptId = this.deptList[this.selectedDeptIndex].deptId
    },

    // 跳转登录页
    handleUserLogin() {
      this.$tab.navigateTo('/pages/login')
    },

    // 获取图形验证码
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled ?? true
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.registerForm.uuid = res.uuid
        }
      })
    },

    // 获取部门列表
    getDeptList() {
      this.$modal.loading('加载部门信息...')
      listDeptPublic().then(res => {
        this.$modal.closeLoading()
        if (res.code === 200) {
          this.deptList = res.data || []
          // 默认选中第一个部门
          if (this.deptList.length > 0) {
            this.selectedDeptIndex = 0
            this.registerForm.deptId = this.deptList[0].deptId
          } else {
            this.$modal.msgError('没有可用的部门，请联系管理员')
          }
        } else {
          this.$modal.msgError(res.msg || '获取部门列表失败')
        }
      }).catch(error => {
        this.$modal.closeLoading()
        console.error('获取部门列表失败:', error)
        this.$modal.msgError('获取部门列表失败')
      })
    },

    // 提交前校验
    handleRegister() {
      if (this.selectedRoleIndex === null) {
        this.$modal.msgError('请选择角色')
      } else if (this.selectedDeptIndex === null) {
        this.$modal.msgError('请选择部门')
      } else if (!this.registerForm.username) {
        this.$modal.msgError('请输入您的账号')
      } else if (this.registerForm.roleKey === 'yewuyuan' && !this.registerForm.employeeId) {
        this.$modal.msgError('请输入工号')
      } else if (this.registerForm.roleKey === 'yewuyuan' && !this.registerForm.level) {
        this.$modal.msgError('请输入等级')
      } else if (!this.registerForm.password) {
        this.$modal.msgError('请输入您的密码')
      } else if (!this.registerForm.confirmPassword) {
        this.$modal.msgError('请再次输入您的密码')
      } else if (
        this.registerForm.password !== this.registerForm.confirmPassword
      ) {
        this.$modal.msgError('两次输入的密码不一致')
      } else if (!this.registerForm.code && this.captchaEnabled) {
        this.$modal.msgError('请输入验证码')
      } else {
        this.$modal.loading('入职中，请耐心等待...')
        this.doRegister()
      }
    },

    // 调用注册 API
    doRegister() {
      // 如果是业务员角色，设置ee为"正常"
      if (this.registerForm.roleKey === 'yewuyuan') {
        this.registerForm.ee = '正常'
      }
      register(this.registerForm)
        .then(() => {
          this.$modal.closeLoading()
          uni.showModal({
            title: '系统提示',
            content: `恭喜你，您的账号 ${this.registerForm.username} 入职成功！`,
            success: res => {
              if (res.confirm) {
                uni.redirectTo({ url: '/pages/login' })
              }
            }
          })
        })
        .catch((error) => {
          this.$modal.closeLoading()
          
          // 解析错误信息，提供友好提示
          let errorMessage = '注册失败，请重试'
          
          if (error && typeof error === 'string') {
            try {
              const errorObj = JSON.parse(error)
              if (errorObj.msg) {
                // 直接使用后端返回的错误信息
                errorMessage = errorObj.msg
              }
            } catch (e) {
              // 如果JSON解析失败，使用原始错误信息
              if (error.includes('Duplicate entry') && error.includes('idx_employee_id')) {
                errorMessage = '工号已存在，请使用其他工号'
              } else if (error.includes('Duplicate entry') && error.includes('user_name')) {
                errorMessage = '用户名已存在，请使用其他用户名'
              } else if (error.includes('Duplicate entry')) {
                errorMessage = '信息重复，请检查输入内容'
              } else {
                errorMessage = error
              }
            }
          }
          
          this.$modal.msgError(errorMessage)
          this.captchaEnabled && this.getCode()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.normal-login-container {
  width: 100%;

  .logo-content {
    width: 100%;
    text-align: center;
    padding-top: 15%;

    image {
      border-radius: 4px;
    }
    .title {
      margin-left: 10px;
      font-size: 21px;
    }
  }

  .login-form-content {
    width: 80%;
    margin: 15% auto 0;
    text-align: center;

    .input-item {
      display: flex;
      align-items: center;
      margin: 20px auto;
      background-color: #f5f6f7;
      height: 45px;
      border-radius: 20px;
      padding: 0 10px;

      .icon {
        font-size: 38rpx;
        margin-right: 10px;
        color: #999;
      }
      .input {
        flex: 1;
        height: 100%;
        line-height: 45px;
        font-size: 14px;
        padding-left: 10px;
      }
      .picker-text {
        height: 45px;
        line-height: 45px;
        font-size: 14px;
        color: #333;
      }
    }

    .register-btn {
      margin-top: 40px;
      height: 45px;
    }
  }

  .xieyi {
    color: #333;
    margin-top: 20px;
  }

  .login-code {
    height: 38px;
    float: right;

    .login-code-img {
      height: 38px;
      width: 200rpx;
      position: absolute;
      margin-left: 10px;
    }
  }
}
</style>
